
# 普通查找
def find(data_list, value):
    '''如果 value 在 data_list 中返回 索引位置，否则返回-1'''
    for index in range(len(data_list)):
        if data_list[index] == value:
            return index
    return -1  # 没找到，返回 -1

L1 = [6, 3, 5, 7, 2, 1, 4, 8]
# print(find(L1, 100))  # -1
# print(find(L1, 2))  # 4

# 二分查找 binary search
def binary_search(data_list, value):
    low = 0
    high = len(data_list) - 1  # high指向最后一个元素
    while low <= high:
        # 计算中间位置 mid 的索引
        mid = (low + high) // 2
        if data_list[mid] == value:
            return mid
        elif value < data_list[mid]:  # value 在中mid的左侧，
            high = mid - 1  # 重新确定上边界为 mid 的下面一个
        elif value > data_list[mid]:
            low = mid + 1
    return -1  # 查找失败 返回 -1

L2 = [11, 22, 33, 44, 55, 66, 77, 88]
print(binary_search(L2, 33))  # 2
print(binary_search(L2, 48))  # -1